package com.chunxuan.langquan.ui.activity.store;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.GsonUtils;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.CarProductEntity;
import com.chunxuan.langquan.dao.bean.ProductDetailEntity;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseAdapter;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseViewHolder;
import com.m7.imkfsdk.KfStartHelper;
import com.m7.imkfsdk.utils.permission.PermissionConstants;
import com.m7.imkfsdk.utils.permission.PermissionXUtil;
import com.m7.imkfsdk.utils.permission.callback.OnRequestCallback;
import com.moor.imkf.requesturl.RequestUrl;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 说明：$
 * <p>
 * date: 2021/3/1 10:57 PM
 *
 * @author syd
 * @version 1.0
 */
public class ProductDetailActivity extends Base2Activity {
    private ImageView iv,iv_product_web_customer;
    private TextView tvTitle;
    private TextView tvPrice;
    private TextView tvAddCard;
    private TextView tvGoOrder;
    private RecyclerView rlv;
    private LinearLayout llCustomer;
    private Adapter adapter;
    private ViewPager vp;
    private List<String> bannerList = new ArrayList<>();
    private VpAdapter vpAdapter;
    public static void actionStart(Context context, String id) {
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra("product_id", id);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_product_web;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iv = findViewById(R.id.iv_product_web_back);
        tvTitle = findViewById(R.id.tv_title);
        tvPrice = findViewById(R.id.tv_price);
        tvAddCard = findViewById(R.id.tv_product_add_to_cart);
        tvGoOrder = findViewById(R.id.tv_product_purchase_now);
        iv_product_web_customer=findViewById(R.id.iv_product_web_customer);
        vp = findViewById(R.id.vp);
        vpAdapter = new VpAdapter();
        vp.setAdapter(vpAdapter);
        rlv = findViewById(R.id.rlv);
        llCustomer = findViewById(R.id.ll_customer);
        adapter = new Adapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rlv.setLayoutManager(linearLayoutManager);
        rlv.setAdapter(adapter);
        requestDetail();
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvAddCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestAddProduct(getIntent().getStringExtra("product_id"));
            }
        });
        iv_product_web_customer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //初始化SDK
                PermissionXUtil.checkPermission(ProductDetailActivity.this, new OnRequestCallback() {
                    @Override
                    public void requestSuccess() {
                        initSdk();
                    }
                }, PermissionConstants.STORE, PermissionConstants.PHONE_STATE);
            }
        });
    }
    /**
     * 初始化SDK
     */
    private void initSdk() {
        // 第一步:初始化help
        final KfStartHelper helper = new KfStartHelper(this);

        RequestUrl.setRequestBasic(RequestUrl.Tencent_REQUEST);

        String userName = "朗权通学用户";
        String uid = "test_uid";

        try {
            userName = Global.USER_INFO.getNickname();
            uid = "langquan_"+Global.USER_INFO.getUser_id();
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*
          第三步:设置参数
          初始化sdk方法，必须先调用该方法进行初始化后才能使用IM相关功能
          @param accessId       接入id（需后台配置获取）
          @param userName       用户名
          @param userId         用户id
         */
        helper.initSdkChat("8e8e12a0-7cc1-11eb-b055-5fc538d90331", userName, uid);
    }
    @SuppressLint("CheckResult")
    public void requestDetail() {
        APIRetrofit.getDefault().productDetail(Global.HEADER, getIntent().getStringExtra("product_id"))
                .compose(RxUtil.<BaseResult2<ProductDetailEntity>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<ProductDetailEntity>>() {
                    @Override
                    public void accept(BaseResult2<ProductDetailEntity> result2) throws Exception {
                        if (result2.isSuccess()) {
                            final ProductDetailEntity entity = result2.getData();
                            tvTitle.setText(entity.getTitle());
                            List<?> couponList=entity.getCoupon();
                            tvPrice.setText("￥" + entity.getSales_price());
                            adapter.setDatas(entity.getImages_text());
                            bannerList = entity.getImages_text();
                            vpAdapter.notifyDataSetChanged();
                            tvGoOrder.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(ProductDetailActivity.this, OrdersActivity.class);
                                    List<CarProductEntity> list = new ArrayList<>();
                                    CarProductEntity productEntity = new CarProductEntity();
                                    productEntity.setImage(entity.getImage());
                                    productEntity.setSales_price(Float.parseFloat(entity.getSales_price()));
                                    productEntity.setNumber(1);
                                    productEntity.setProduct_id(entity.getProduct_id());
                                    productEntity.setCoupon(couponList);
                                    list.add(productEntity);
                                    intent.putExtra("data", GsonUtils.toJson(list));
                                    startActivity(intent);
                                }
                            });
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        throwable.printStackTrace();
                        ToastUtils.showShort("获取商品详情失败");
                    }
                });
    }


    @SuppressLint("CheckResult")
    public void requestAddProduct(String id) {
        APIRetrofit.getDefault().addProduct(Global.HEADER, id)
                .compose(RxUtil.<BaseResult2<String>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<String>>() {
                    @Override
                    public void accept(BaseResult2<String> result2) throws Exception {
                        if (result2.isSuccess()) {
                            ToastUtils.showShort(result2.getMsg());
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        throwable.printStackTrace();
                        ToastUtils.showShort("添加商品失败");
                    }
                });
    }

    static class Adapter extends BaseAdapter<String> {

        @NonNull
        @Override
        public BaseViewHolder<String> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view = inflater.inflate(R.layout.item_rlv_store_iv, parent, false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }
    }

    static class ViewHolder extends BaseViewHolder<String> {

        @Override
        public void bindViewHolder(String value) {
            GlideUtil.loadImg(value, (ImageView) itemView);
        }

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    // banner adapter
    private class VpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView iv = new ImageView(ProductDetailActivity.this);
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

//            iv.setImageResource(R.drawable.home_top_banner);
            GlideUtil.loadImg(bannerList.get(position), iv);

            container.addView(iv);
            return iv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }
    }
}
